from django.shortcuts import render, redirect, reverse
from django.views.generic import View
from django.http import HttpResponse
from .models import User


class IndexView(View):
    def get(self, request, *args, **kwargs):
        print('3.IndexView到达视图后...')
        if request.frontuser:
            print('当前登录用户telphone：', request.frontuser.telphone)
        return render(request, 'index.html')


class ListView(View):
    def get(self, request, *args, **kwargs):
        if request.frontuser:
            print('当前登录用户telphone：', request.frontuser.telphone)
        return render(request, 'list.html')


class SigninView(View):
    def get(self, request, *args, **kwargs):
        return render(request, 'signin.html')

    def post(self, request, *args, **kwargs):
        telphone = request.POST.get('telphone')
        password = request.POST.get('password')
        user = User.objects.filter(telphone=telphone, password=password).first()
        if user:
            # TODO: 设置登录人session
            request.session['user_id'] = user.id
            request.session.set_expiry(86400)
            return redirect(reverse('index'))
        else:
            return HttpResponse('用户名或密码错误')
